/*
 * 结构体与文件操作
 * booksave
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXTITLE 40
#define MAXAUTL 40
#define MAXBKS 10

struct book
{
    char title[MAXTITLE];
    char author[MAXAUTL];
    float value;
};

int main()
{
    struct book library[MAXBKS]; //结构数组
    int count = 0;
    int index, filecount;

    FILE *pb;
    int size = sizeof(struct book);

    if ((pb = fopen("book.dat", "a+b")) == NULL)
    {
        fputs("Cant't open book.dat file.\n", stderr);
        exit(1);
    }

    rewind(pb); //定位到文件开始处

    while (count < MAXBKS && fread(&library[count], size, 1, pb) == 1)
    {
        if (count == 0)
            puts("Current contents of  book.dat:\n"); //是否有换行？没有

        printf("%s\n%s\n$ %.2f\n\n", library[count].title, library[count].author, library[count].value);
        count++;
    }

    filecount = count; //用来保存已读结构的数目
    if (count == MAXBKS)
    {
        fputs("The book.dat file is full.\n", stderr);
        exit(2);
    }

    puts("Please add new book titles:"); //新增书目

    while (count < MAXBKS && gets(library[count].title) != NULL && library[count].title[0] != '\0')
    {
        puts("Now enter the author.");
        gets(library[count].author);
        puts("Now enter the value.");
        scanf("%f", &library[count++].value);
        while (getchar() != '\n')
            continue; //清空输入行
        if (count < MAXBKS)
            puts("    Enter the next title.");
    }
    if (count > 0)
    {
        puts("Here is the list of your books:");
        for (index = 0; index < count; index++)
            printf("%s\n%s\n$ %.2f\n\n", library[index].title, library[index].author, library[index].value);
        fwrite(&library[filecount], size, count - filecount, pb); //向文件写入内容。count - filecount表示要加入的新书的数目
    }                                                             //&library[filecount]为数组中第一个新输入的结构的地址，复制就从这一点开始
    else
        puts("No books!\n");
    fclose(pb);

    return 0;
}
